package zhh.tangbao.websocket.client.impl;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import zhh.tangbao.system.utils.ApplicationContextUtil;
import zhh.tangbao.user.cache.UserCache;
import zhh.tangbao.user.vo.UserVo;
import zhh.tangbao.websocket.WebSocketServiceType;
import zhh.tangbao.websocket.client.WebSocketClient;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * <p>
 *     websocket客户端
 *     通过用户ID为参数实现websocket连接
 *     当有websocket连接时会自动创建一个WebSocketClient对象
 *     spring无法解决原型循环依赖问题，所有原型模式的bean需要注意
 * </p>
 * @author 粥灰灰
 * <p>2023/3/28</p>
 */

@ServerEndpoint(value = "/websocket/connect/{token}/{key}")
@Component
@Slf4j
public class MessageClient extends WebSocketClient {

    private final UserCache userCache = ApplicationContextUtil.getBean(UserCache.class);



    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token, @PathParam("key") String key) {
        UserVo loginData = userCache.getLoginData(token, key);
        Assert.notNull(loginData, "用户登录授权已过期");
        this.id = loginData.getId();
        this.session = session;
        addClient(WebSocketServiceType.MESSAGE, this.id, this);
    }

    @OnClose
    public void onClose() {
        removeClient(WebSocketServiceType.MESSAGE, this.id);
    }

    @OnError
    public void onError(Throwable throwable) {
        log.error(throwable.getMessage());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("消息服务，收到客户端消息：" + message);
    }

}
